package ldh.maker.db;

import ldh.maker.util.UiUtil;
import ldh.maker.vo.JavafxSetting;
import ldh.maker.vo.TreeNode;

import java.sql.*;

/**
 * Created by ldh on 2017/4/16.
 */
public class JavafxSettingDb {

    public static JavafxSetting loadData(TreeNode treeNode, String dbName) throws SQLException {
        JavafxSetting data = null;
        Connection connection = UiUtil.H2CONN;
        String sql = "select * from javafx_setting where tree_node_id = ? and db_name = ?";
        PreparedStatement statement = connection.prepareStatement(sql);
        statement.setInt(1, treeNode.getId());
        statement.setString(2, dbName);
        ResultSet rs = statement.executeQuery();
        if(rs.next()){
            data = new JavafxSetting();
            data.setPojo(rs.getString("pojo"));
            data.setDbName(rs.getString("db_name"));
            data.setTreeNodeId(rs.getInt("tree_node_id"));
            data.setId(rs.getInt("id"));
        }
        statement.close();
        return data;
    }

    public static void save(JavafxSetting data, TreeNode treeNode) throws SQLException {
        Connection connection = UiUtil.H2CONN;
        String sql = "insert into javafx_setting(pojo, db_name, tree_node_id) values(?, ?, ?)";
        PreparedStatement statement = connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
        statement.setString(1, data.getPojo());
        statement.setString(2, data.getDbName());
        statement.setInt(3, treeNode.getId());
        statement.executeUpdate();
        statement.close();
    }

    public static void update(JavafxSetting data, TreeNode treeNode) throws SQLException {
        Connection connection = UiUtil.H2CONN;
        String sql = "update javafx_setting set pojo=? where tree_node_id=? and db_name = ?";
        PreparedStatement statement = connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
        statement.setString(1, data.getPojo());
        statement.setInt(2, treeNode.getId());
        statement.setString(3, data.getDbName());
        statement.executeUpdate();
        statement.close();
    }
}
